package org.corey.share.db.service;

import java.util.Collections;
import java.util.List;

import org.corey.share.db.dao.ArticleDao;
import org.corey.share.db.dao.BaseDao;
import org.corey.share.db.entity.ArticleCatogory;
import org.corey.share.db.manager.DefaultDaoFactory;
import org.corey.share.db.manager.EM;

public class ArticleCatogoryServiceImpl implements ArticleCatogoryService {
	private BaseDao dao = new DefaultDaoFactory().creatBaseDao();
	private ArticleDao articleDao = new DefaultDaoFactory().createArticleDao();

	public boolean addArticleCatogory(ArticleCatogory newCatogory) {
		if (newCatogory == null) {
			throw new IllegalArgumentException();
		}
		EM.beginTransaction();
		boolean result = dao.save(newCatogory);
		EM.commitTransaction();
		return result;
	}

	public boolean deleteArticleCatogory(Long catogoryId) {
		if (catogoryId == null) {
			throw new IllegalArgumentException();
		}
		EM.beginTransaction();
		ArticleCatogory type = this.getArticleCatogory(catogoryId);
		Boolean result = dao.remove(type);
		EM.commitTransaction();
		return result;
	}

	public boolean deleteArticleCatogory(ArticleCatogory catogory) {
		if (catogory == null) {
			throw new IllegalArgumentException();
		}
		EM.beginTransaction();
		boolean result = dao.remove(catogory);
		EM.commitTransaction();
		return result;
	}

	@SuppressWarnings("unchecked")
	public List<ArticleCatogory> getAllArticleCatogory(Long userId) {
		List<ArticleCatogory> catogories = Collections.EMPTY_LIST;
		if (userId == null) {
			catogories = dao.findAll(0, 0, ArticleCatogory.class, "writeDate desc")
					.getPageData();
		} else {
			catogories = dao.findAll(0, 0, ArticleCatogory.class, userId, "writeDate desc")
					.getPageData();
		}
		for (int index = 0; index < catogories.size(); index++) {
			ArticleCatogory type = catogories.get(index);
			type
					.setArticleCount(articleDao.getArticleCountInCatogory(type
							.getId()));
		}
		return catogories;
	}

	public ArticleCatogory getArticleCatogory(Long id) {
		if (id == null) {
			throw new IllegalArgumentException();
		}
		ArticleCatogory catogory = (ArticleCatogory) dao.load(id, ArticleCatogory.class);
		catogory.setArticleCount(articleDao.getArticleCountInCatogory(catogory.getId()));
		return catogory;
	}

	public boolean modifyArticleCatogory(ArticleCatogory type) {
		if (type == null) {
			throw new IllegalArgumentException();
		}
		EM.beginTransaction();
		boolean result = dao.update(type);
		EM.commitTransaction();
		return result;
	}

}
